package com.tan00xu.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tan00xu.dao.ArticleMapper;
import com.tan00xu.pojo.Article;
import com.tan00xu.utils.CmdOutputInformationUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {

    /**
     * 更新阅读数
     * @param articleMapper
     * @param article
     */
    @Async("taskExecutor")
    public void updateArticelViewConts(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaQueryWrapper<Article> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Article::getId, article.getId());
        //为了线程安全，添加乐观锁
        updateWrapper.eq(Article ::getViewCounts, viewCounts);
        articleMapper.update(articleUpdate, updateWrapper);
        try {
            Thread.sleep(5000);
            CmdOutputInformationUtils.info("更新完成了……");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


}
